<?php
/**
 * upload文件浏览器
 *
 * @version      0.0.0
 * @author      by huwhois
 * @time        2017/11/27
 */

namespace app\admin\controller;

use think\Request;

class Filebrowser extends Base
{

    public function index($activepath = '', $sort = null)
    {
        // echo $activepath;exit;
        if ($activepath=='') {
            $activepath='uploads';
        }
//获取路径参数
        $inpath = "";
        $activepath = str_replace("..", "", $activepath);
        // $activepath = str_replace("\\", "/", $activepath);
        
        $inpath = ROOT_PATH . 'public/' . $activepath;
        $inpath = str_replace("\\", "/", $inpath);

//  按名称排序读出目录名称 
        $dirhandle = dir($inpath);
        define("BKM", 1024);
        $dirs = $files = array();
        
        while (($file = $dirhandle->read()) !== false) {
        //读目录略过./..
            if ($file == "." || $file == "..") {
                continue;
            } elseif (is_dir("$inpath/$file")) {
        //win里面需要转码(win是gb2312存储的文件名的),linux不用
        //$dirs[] = $file;
                $dirs[] = iconv("gb2312", "utf-8", $file);
            } elseif (!is_dir("$inpath/$file")) {
                $arr =  array();
                $arrf = array();
        //获取文件大小b/k/m
                @$filesize = floatval(filesize("$inpath/$file"));
                if ($filesize>BKM) {
                    $filesize =  round($filesize/BKM, 2);
                    if ($filesize>BKM) {
                        $filesize = round($filesize/BKM, 2);
                        $filesize .="M";
                    } else {
                        $filesize .="K";
                    }
                } else {
                    $filesize .="B";
                }
        //获取最后修改时间
                @$filetime = filemtime("$inpath/$file");
                @$filetime = date("Y-m-d H:i:s", $filetime);
        //win里面需要转码(win是gb2312存储的文件名的),linux不用
        //$arr['name'] = $file;
                $arr['name'] = iconv("gb2312", "utf-8", $file);
                $arr['size'] = $filesize;
                $arr['time'] = $filetime;
                $arrf = pathinfo($file);
                $arr['extension'] = $arrf['extension'];
                $files[] = $arr;
            }
        }
        $dirhandle->close();
        
        @(isset($rsort) && $sort == 'rsort') ?  rsort($dirs) : sort($dirs);
        // @sort($dirs);
        // echo "<pre>";
        // print_r($dirs);
        // print_r($files);
        // exit;
//计数
        $counts = count($dirs)+count($files);
        $this->assign('counts', $counts);
//上级目录                
        $tmp = preg_replace("#[\/][^\/]*$#i", "", $activepath);
        $this->assign('activeurl', $tmp);
//当前目录
        $this->assign("activepath", $activepath);
//当前目录下得目录
        $this->assign('dirs', $dirs);
//当前目录下的文件
        $this->assign("files", $files);
        return $this->fetch();
    }

//查看图片    
    public function preview($imagename = "")
    {
    }

//删除图片
    public function del($activepath = '', $filename = '')
    {
        $activepath = str_replace('/', DS, $activepath);
        if (Request::instance()->isAjax()) {
            if (unlink(ROOT_PATH.'public'.DS.$activepath.DS.$filename)) {
                return ['status'=>1,'msg'=>'success'];
            } else {
                return ['status'=>0,'msg'=>'failed'];
            }
        }
    }

//上传图片    
    public function upload()
    {
        if (Request::instance()->isPOST()) {
            $isthumb = input('post.')['isthumb'];
            $files = request()->file('image');
            // var_dump($files);exit;
            foreach ($files as $file) {
                $info = $file->validate(['size'=>1048576,'ext'=>'jpg,png,gif,jpeg'])->move(ROOT_PATH . 'public' . DS . 'uploads');
                if ($info) {
                //是否生成缩略图??
                    if ($isthumb) {
                        //生成缩略图
                        $filename = $info->getSaveName();
                        $filename = str_replace("\\", '/', 'uploads' . DS . $filename);
                        $thumbname = get_thumb($filename);
                        $thumbname = str_replace("\\", '/', $thumbname);

                        if ($thumbname) {
                            continue;
                        } else {
                            $this->error('上传失败');
                        }
                    } else {
                        continue;
                    }
                } else {
                    $this->error($info->getExtension());
                }
            }
            $this->success('上传成功', 'index');
        } else {
            return $this->fetch();
        }
    }

//上传缩略图
    public function uploadThumb()
    {
        //获取上传图片
        $file = request()->file('upload_file');
        // 移动到框架应用根目录/public/uploads/ 目录下自动生成文件名
        $info = $file->validate(['size'=>1048576,'ext'=>'jpg,png,gif,jpeg'])->move(ROOT_PATH . 'public' . DS . 'uploads');
        if ($info) {
            // echo $info->getSaveName();
            $filename = $info->getSaveName();
            //生成缩略图
            $thumbname = get_thumb('uploads' . DS . $filename);
            $thumbname = str_replace("\\", '/', $thumbname);
            if ($thumbname) {
                return ['status'=>1,'imgname'=>$thumbname];
            } else {
                return ['status'=>0,'msg'=>"缩略图生成失败"];
            }
        } else {
            $msg=$info->getError();
            return ['status'=>0,'msg'=>$msg];
        }
    }




//图片选择
    public function selectThumb($step = 0, $activepath = '', $sort = null)
    {
    // echo $activepath;exit;
        if ($activepath=='') {
            $activepath='uploads';
        }
    //获取路径参数
            $inpath = "";
            $activepath = str_replace("..", "", $activepath);
            // $activepath = str_replace("\\", "/", $activepath);
            
            $inpath = ROOT_PATH . 'public/' . $activepath;
            $inpath = str_replace("\\", "/", $inpath);
    
    //  按名称排序读出目录名称
            $dirhandle = dir($inpath);
            define("BKM", 1024);
            $dirs = $files = array();
            
        while (($file = $dirhandle->read()) !== false) {
            //读目录略过./..
            if ($file == "." || $file == "..") {
                continue;
            } elseif (is_dir("$inpath/$file")) {
            //win里面需要转码(win是gb2312存储的文件名的),linux不用
            //$dirs[] = $file;
                $dirs[] = iconv("gb2312", "utf-8", $file);
            } elseif (!is_dir("$inpath/$file")) {
                $arr =  array();
                $arrf = array();
            //获取文件大小b/k/m
                @$filesize = floatval(filesize("$inpath/$file"));
                if ($filesize>BKM) {
                    $filesize =  round($filesize/BKM, 2);
                    if ($filesize>BKM) {
                        $filesize = round($filesize/BKM, 2);
                        $filesize .="M";
                    } else {
                        $filesize .="K";
                    }
                } else {
                    $filesize .="B";
                }
            //获取最后修改时间
                @$filetime = filemtime("$inpath/$file");
                @$filetime = date("Y-m-d H:i:s", $filetime);
            //win里面需要转码(win是gb2312存储的文件名的),linux不用
            //$arr['name'] = $file;
                $arr['name'] = iconv("gb2312", "utf-8", $file);
                $arr['size'] = $filesize;
                $arr['time'] = $filetime;
                $arrf = pathinfo($file);
                $arr['extension'] = $arrf['extension'];
                $files[] = $arr;
            }
        }
            $dirhandle->close();
            
            @(isset($rsort) && $sort == 'rsort') ?  rsort($dirs) : sort($dirs);
            // @sort($dirs);
            // echo "<pre>";
            // print_r($dirs);
            // print_r($files);
            // exit;
    //当前缩略图选择方法
            $this->assign('step', $step);
    //计数
            $counts = count($dirs)+count($files);
            $this->assign('counts', $counts);
    //上级目录
            $tmp = preg_replace("#[\/][^\/]*$#i", "", $activepath);
            $this->assign('activeurl', $tmp);
    //当前目录
            $this->assign("activepath", $activepath);
    //当前目录下得目录
            $this->assign('dirs', $dirs);
    //当前目录下的文件
            $this->assign("files", $files);
            return $this->fetch('select_thumb');
    }

//判断(远程)文件是否为图片    
    public function isImg($filename = '')
    {
        if (Request::instance()->isAjax()) {
            try {
                $mimetype = exif_imagetype($filename);
                // var_dump($mimetype);exit;
                if ($mimetype == IMAGETYPE_GIF || $mimetype == IMAGETYPE_JPEG || $mimetype == IMAGETYPE_PNG) {
                    return ['status'=>1,'msg'=>'图片地址可用'];
                //     $image = \think\Image::open($filename);
                //     $fileinfo= pathinfo($filename);
                //     $thumbname = $fileinfo['dirname'].DS.'thumb'.DS.$fileinfo['filename'].'_thumb.'.$fileinfo['extension'];
                //     // echo $thumbname;exit;
                //     $test=$image->thumb($width,$height,\think\Image::THUMB_FIXED)->save($thumbname);
                } else {
                    return ['status'=>0,'msg'=>'该图片不合法'];
                }
            } catch (\Exception $e) {
                return ['status'=>0,'msg'=>'地址不合法'];
            }
        }
    }
}
